package com.ruiaa.meeting.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruiaa.meeting.common.BusinessException;
import com.ruiaa.meeting.common.CommonResponse;
import com.ruiaa.meeting.common.Constant;
import com.ruiaa.meeting.common.ResponseCode;
import com.ruiaa.meeting.model.Api;
import com.ruiaa.meeting.model.MeetingRoom;
import com.ruiaa.meeting.model.Reservation;
import com.ruiaa.meeting.model.User;
import com.ruiaa.meeting.model.dto.ReservationDto;
import com.ruiaa.meeting.model.vo.ReservationVo;
import com.ruiaa.meeting.model.vo.UserVo;
import com.ruiaa.meeting.persistence.MeetingRoomMapper;
import com.ruiaa.meeting.persistence.ReservationMapper;
import com.ruiaa.meeting.service.ApiService;
import com.ruiaa.meeting.service.ReservationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * @author chenhuaiyi
 * @date 2022-11-05 15:32
 */
@Service
public class ReservationServiceImpl implements ReservationService {

    @Autowired
    private ReservationMapper reservationMapper;

    @Autowired
    private MeetingRoomMapper meetingRoomMapper;

    @Autowired
    private ApiService apiService;

    //获取全部信息
    @Override
    public CommonResponse<List<Reservation>> getAllReservation() {
        QueryWrapper<Reservation> queryWrapper = new QueryWrapper<>();
        List<Reservation> reservationList = reservationMapper.selectList(queryWrapper);
        if (reservationList != null) {
            List<Api> relationalApis = apiService.getRelationalApis(16);
            return CommonResponse.createForSuccessIncludeApis(reservationList,relationalApis);
        }
        return CommonResponse.createForError("查询失败");
    }

    //按需获取
    @Override
    public CommonResponse<List<Reservation>> getReservation(ReservationDto reservation) {
        QueryWrapper<Reservation> queryWrapper = new QueryWrapper<>();

        if (reservation.getReserveId()!=null) queryWrapper.eq("reserve_id", reservation.getReserveId());
        if (reservation.getRoomId()!=null) queryWrapper.eq("room_id", reservation.getRoomId());
        if (!reservation.getUsername().equals("")) queryWrapper.eq("username", reservation.getUsername());
        if (reservation.getReserveTime()!=null) queryWrapper.eq("reserve_time", reservation.getReserveTime());
        if (reservation.getStartTime()!=null) queryWrapper.eq("start_time", reservation.getStartTime());
        if (reservation.getEndTime()!=null) queryWrapper.eq("end_time", reservation.getEndTime());
        if (reservation.getState()!=null) queryWrapper.eq("state", reservation.getState());

        List<Reservation> reservationList = reservationMapper.selectList(queryWrapper);
        if (reservationList.size()>0) {
            List<Api> relationalApis = apiService.getRelationalApis(18);
            return CommonResponse.createForSuccessIncludeApis(reservationList, relationalApis);
        }

        return CommonResponse.createForError("未查询到相关信息");
    }

    //通过指定会议，并返回通过会议三个id
    @Override
    public CommonResponse<ReservationVo> passReservation(Integer reserveId) {
        QueryWrapper<Reservation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("reserve_id", reserveId);
        Reservation reservation = reservationMapper.selectOne(queryWrapper);
        if (reservation != null) {
            if (!Objects.equals(reservation.getState(), Constant.RESERVATION_STATE.WAIT_REVIEW)) {
                throw new BusinessException(ResponseCode.ERROR.getCode(), "该会议不处于待审核状态");
            }
            reservation.setState(Constant.RESERVATION_STATE.PASSED);

            UpdateWrapper<Reservation> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("reserve_id", reservation.getReserveId());
            updateWrapper.set("state", reservation.getState());

            int rows = reservationMapper.update(reservation, updateWrapper);
            if (rows > 0) {
                return CommonResponse.createForSuccess(reservationToreservatnioVo(reservation));
            }
        } else throw new BusinessException(ResponseCode.ERROR.getCode(), "预约会议不存在");

        return CommonResponse.createForError("审核失败");
    }

    //拒绝
    @Override
    public CommonResponse<ReservationVo> rejectReservation(Integer reserveId) {
        QueryWrapper<Reservation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("reserve_id", reserveId);
        Reservation reservation = reservationMapper.selectOne(queryWrapper);
        if (reservation != null) {
            if (!Objects.equals(reservation.getState(), Constant.RESERVATION_STATE.WAIT_REVIEW)) {
                throw new BusinessException(ResponseCode.ERROR.getCode(), "该会议不处于待审核状态");
            }
            reservation.setState(Constant.RESERVATION_STATE.REFUSED);

            UpdateWrapper<Reservation> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("reserve_id", reservation.getReserveId());
            updateWrapper.set("state", reservation.getState());

            int rows = reservationMapper.update(reservation, updateWrapper);
            if (rows > 0) {
                return CommonResponse.createForSuccess(reservationToreservatnioVo(reservation));
            }
        } else throw new BusinessException(ResponseCode.ERROR.getCode(), "预约会议不存在");

        return CommonResponse.createForError("拒绝操作失败");
    }

    //清除过期预约
    @Override
    public CommonResponse<Object> clearReservation() {
        QueryWrapper<Reservation> queryWrapper = new QueryWrapper<>();
        UpdateWrapper<Reservation> updateWrapper = new UpdateWrapper<>();
        List<Reservation> reservationList = reservationMapper.selectList(queryWrapper);
        if (reservationList != null) {
            for (Reservation reservation : reservationList) {
                if (LocalDateTime.now().isAfter(reservation.getEndTime())) {
                    reservation.setState(Constant.RESERVATION_STATE.OUT_OF_DATE);
                    updateWrapper.eq("reserve_id", reservation.getReserveId());
                    updateWrapper.set("state", reservation.getState());

                    reservationMapper.update(reservation, updateWrapper);
                }
            }

            queryWrapper.eq("state", Constant.RESERVATION_STATE.OUT_OF_DATE);
            reservationMapper.delete(queryWrapper);

            return CommonResponse.createForSuccess("清除过期预约成功");
        }
        return CommonResponse.createForError("清除过期预约失败");
    }

    //进行会议预约
    @Override
    public CommonResponse<Object> reserveReservation(Integer roomId, LocalDateTime startTime, LocalDateTime endTime) {
        QueryWrapper<Reservation> queryWrapper = new QueryWrapper<>();
        Reservation reservation=new Reservation();

        String username=(String) StpUtil.getLoginId();

        reservation.setRoomId(roomId);
        reservation.setUsername(username);
        reservation.setStartTime(startTime);
        reservation.setEndTime(endTime);

        queryWrapper.eq("room_id",reservation.getRoomId());
        queryWrapper.eq("state",Constant.RESERVATION_STATE.WAIT_REVIEW).or().eq("state",Constant.RESERVATION_STATE.PASSED);

        QueryWrapper<MeetingRoom> queryWrapper1 =new QueryWrapper<>();
        //等会议室模块做完 找会议室是否存在



        List<Reservation> reservationList = reservationMapper.selectList(queryWrapper);

        if (reservationList!=null){
            if (reservation.getEndTime().isBefore(reservation.getStartTime())||reservation.getStartTime().isBefore(LocalDateTime.now()))
                return CommonResponse.createForError("起始结束时间设定有误");

            for (Reservation reservation1 : reservationList) {
               if (!(reservation.getEndTime().isBefore(reservation1.getStartTime())||reservation.getStartTime().isAfter(reservation1.getEndTime())))
                   return CommonResponse.createForError("预约时间冲突");
            }
        }

        reservation.setReserveTime(LocalDateTime.now());
        reservation.setState(Constant.RESERVATION_STATE.WAIT_REVIEW);

        int rows=reservationMapper.insert(reservation);
        if (rows>0) {
            List<Api> relationalApis = apiService.getRelationalApis(21);
            return CommonResponse.createForSuccessIncludeApis("已预约，等待管理员审核", relationalApis);
        }

        return CommonResponse.createForError("预约失败");
    }

    //取消已预约会议
    @Override
    public CommonResponse<Object> cancelReservation(Integer reserveId) {
        String username = (String) StpUtil.getLoginId();
        if (username != null) {
            QueryWrapper<Reservation> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("reserve_id", reserveId);
            queryWrapper.eq("username", username);

            int rows = reservationMapper.delete(queryWrapper);
            if (rows > 0) {
                return CommonResponse.createForSuccess("取消该预约会议成功");
            }
        }
        return CommonResponse.createForError("该会议不存在或已取消");
    }


    //转化
    private ReservationVo reservationToreservatnioVo(Reservation reservation) {
        ReservationVo reservationVo = new ReservationVo();
        reservationVo.setReserveId(reservation.getReserveId());
        reservationVo.setRoomId(reservation.getRoomId());
        reservationVo.setUsername(reservation.getUsername());
        reservationVo.setState(reservation.getState());

        return reservationVo;
    }
}